//
//  AppContext.h
//  ChunLaiZhuangClient
//
//  Created by xielihui on 16/3/30.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "AccountManager.h"
#import "AccountModel.h"
#import "AppContext.h"

@interface AppContext () <AccountManagerDelegate>

@property(nonatomic, readwrite) AccountManager *accountManager;

@end


@implementation AppContext {
    
}
+ (instancetype)instance {
    static AppContext *_instance = nil;
    
    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    
    return _instance;
}

- (void)dealloc {
    [self cleanupNotifications];
}

- (void)setup {
    [self setupNotifications];
    if (self.account) {
        [self.accountManager refreshAccountInfo];
    }
}


- (AccountModel *)account {
    return self.accountManager.account;
}

- (AccountManager *)accountManager {
    if (!_accountManager) {
        _accountManager = [[AccountManager alloc] init];
        [_accountManager setAccountManagerDelegate:self];
    }
    
    return _accountManager;
}

#pragma mark Notification
- (void)setupNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userLoginNotification:)
                                                 name:ACCOUNT_DID_LOGIN_NOTIFICATION
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userLogoutNotification:
                                                                ) name:ACCOUNT_WILLDID_LOGOUT_NOTIFICATION
                                               object:nil];
}

- (void)cleanupNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)userLoginNotification:(NSNotification *)notification {
    
}

#pragma mark - accountManagerApiDelegate
- (void)accountManagerUserLogout{
    [self clearAccountCache];
}

- (void)clearAccountCache {
    [[NSFileManager defaultManager] removeItemAtPath:[APP_CONTEXT.accountManager pathOfCacheFile] error:nil];
}

- (void)userLogoutNotification:(NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] postNotificationName:ACCOUNT_DID_LOGOUT_NOTIFICATION object:nil];
}


@end